package org.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.example.entity.Role;
import org.example.entity.UserRole;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 用户角色关联Mapper接口
 */
@Mapper
public interface UserRoleMapper extends BaseMapper<UserRole> {
    
    /**
     * 根据用户ID查询用户平台端角色列表
     */
    @Select("SELECT r.* FROM roles r " +
            "INNER JOIN user_role_platform_relations ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.is_active = 1")
    List<Role> getPlatformRolesByUserId(@Param("userId") Long userId);
    
    /**
     * 根据用户ID和公司ID查询用户企业端角色列表
     */
    @Select("SELECT r.* FROM roles r " +
            "INNER JOIN user_role_company_relations ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND ur.company_id = #{companyId} AND r.is_active = 1")
    List<Role> getEnterpriseRolesByUserId(@Param("userId") Long userId, @Param("companyId") Long companyId);
    
    /**
     * 根据用户ID查询用户角色列表（兼容方法，优先查询平台端角色）
     */
    @Select("SELECT r.* FROM roles r " +
            "INNER JOIN user_role_platform_relations ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.is_active = 1 " +
            "UNION " +
            "SELECT r.* FROM roles r " +
            "INNER JOIN user_role_company_relations ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.is_active = 1")
    List<Role> getRolesByUserId(@Param("userId") Long userId);
    
    /**
     * 根据用户ID查询用户主要角色（从users表的primary_role_id字段）
     */
    @Select("SELECT r.* FROM roles r " +
            "INNER JOIN users u ON r.id = u.primary_role_id " +
            "WHERE u.id = #{userId} AND r.is_active = 1")
    Role getPrimaryRoleByUserId(@Param("userId") Long userId);
    
    /**
     * 根据用户ID查询用户角色关联列表（平台端）
     */
    @Select("SELECT * FROM user_role_platform_relations WHERE user_id = #{userId}")
    List<UserRole> getPlatformUserRolesByUserId(@Param("userId") Long userId);
    
    /**
     * 根据用户ID和公司ID查询用户角色关联列表（企业端）
     */
    @Select("SELECT * FROM user_role_company_relations WHERE user_id = #{userId} AND company_id = #{companyId}")
    List<UserRole> getEnterpriseUserRolesByUserId(@Param("userId") Long userId, @Param("companyId") Long companyId);
}
